#pragma comment (linker, "/STACK:100000000")
#include "testlib.h"
#include <stdio.h>
#include <string>
#include <vector>
using namespace std;
#define N 5010
int a[N][26], u[N];
char s[N];
vector <int> m[N];
bool dfs(int i)
{
	int j;
	u[i]=1;
	for(j=0; j<m[i].size(); j++)
		if(u[m[i][j]]==1) return 1;
		else if(!u[m[i][j]] && dfs(m[i][j])) return 1;
	u[i]=2;
	return 0;
}
int main(int argc, char * argv[])
{
    registerTestlibCmd(argc, argv);
    int n, k, i, j, l;
	string ss, c;
	ss=inf.readWord();
	n=ouf.readInt();
	if(n!=ss.size()+1) quitf(_wa, "number of nodes is expected %d, found %d", ss.size()+1, n);
	k=ouf.readInt();
	if(k<0) quitf(_pe, "nuber of edges must be positive");
	for(l=k; k--; )
	{
		i=ouf.readInt();
		if(i<1 || i>n) quitf(_pe, "invalid node %d", i);
		j=ouf.readInt();
		if(j<1 || j>n) quitf(_pe, "invalid node %d", j);
		m[i-1].push_back(j-1);
		c=ouf.readWord();
		if(c.size()!=1 || c[0]<'a' || c[0]>'z') quitf(_pe, "invalid symbol %s", c.c_str());
		a[i-1][c[0]-'a']=j-1;
	}
	for(i=0; i<n; i++)
		if(!u[i] && dfs(i)) quitf(_wa, "there is a loop");
	for(i=0; i<n-1; s[i]=ss[i]-'a', i++);
	for(i=0; i<n-1; i++)
		for(k=0, j=i; j<n-1; j++)
			if(!a[k][s[j]]) quitf(_wa, "suffix %s is not accepted", ss.substr(i).c_str());
			else k=a[k][s[j]];
	quitf(_ok, "%d nodes, %d edges", n, l);
}